<script lang="ts" setup>
import { ref, h, onBeforeMount, nextTick, reactive } from "vue";
import {
  VxeFormPropTypes,
  VxeFormInstance,
  VxeModalInstance,
  VxeFormProps
} from "vxe-pc-ui";
import { withdrawalGetInfo } from "@/api/capital/capital";
import { uploadTheInvoice } from '@/api/invoice/invoice'
const emits = defineEmits<{ (e: "reload"): void }>();
const vxeModalRef = ref<VxeModalInstance>();
import { ElMessage,UploadProps,UploadUserFile } from "element-plus";
import { upload } from "@/utils/uploadCos";
import type { FormInstance, FormRules } from 'element-plus'
import { Remove,CirclePlus } from "@element-plus/icons-vue";

const modalOptions = reactive<{
  modalValue: boolean;
  modalTitle: string;
  canSubmit: boolean;
}>({
  modalValue: false,
  modalTitle: "",
  canSubmit: true
});

const showModal = (title: string, canSubmit?: boolean): void => {
  modalOptions.modalTitle = title;
  modalOptions.modalValue = true;
  modalOptions.canSubmit = canSubmit ?? true;
};
const detailid = ref<number | string>();
const showAddModal = (id:number) => {
  showModal(`查看`);
  detailid.value = id;
  // nextTick(() => {
  //   formRef.value.clearValidate();
  // });
};
// const handleSubmit = async () => {
//   const validate = await ruleFormRef.value.validate();
//   if (!validate) {
//     addBackstage(form).then(() => {
//       modalOptions.modalValue = false;
//       emits("reload");
//     });
//   }
// };
const ruleFormRef = ref<FormInstance>()
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      form.id = detailid.value;
      uploadTheInvoice(form).then(res=>{
        ElMessage.info(res?.msg)
        modalOptions.modalValue = false;
        emits("reload");
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

onBeforeMount(() => {
  
});
defineExpose({ showAddModal });
 
const form = reactive<any>({
  invoiceUrl: '',
  typeOfInvoiceIssued: 1,//1 纸质 2 电子
  invoiceUploadType: 1,// 1 文件 2 链接
  domains: [{
    value: '',
    key: 1
  }],
  id: ''
});
// 添加票据链接input 
const addDomain = () => {
  form.domains.push({
    key: Date.now(),
    value: '',
  })
}
// 删除票据链接 
const removeDomain = (item: DomainItem) => {
  const index = form.domains.indexOf(item)
  if (index !== -1) {
    form.domains.splice(index, 1)
  }
}
// 上传  

const fileList = ref<UploadUserFile[]>([]);
const handleRemove: UploadProps["onRemove"] = (file, uploadFiles) => {
  console.log(file, uploadFiles);
  console.log(fileList.value);
  form.invoiceUrl = "";
};
const toupload = (params: any) => {
  upload(params.file, res => {
    let index = res.lastIndexOf("/");
    let filename = res.substring(index + 1, res.length);
    let obj = {
      url: `https://${res}`,
      name: filename
    }
    fileList.value.push(obj)
    fileList.value.forEach((item,index)=>{
      if(item.status == 'ready'){
        fileList.value.splice(index,1)
      }
    })
    form.invoiceUrl = obj.url;
  });
};
</script>
<template>
  <vxe-modal
    ref="vxeModalRef"
    v-model="modalOptions.modalValue"
    width="600"
    showFooter
    :title="modalOptions.modalTitle"
  >
    <template #default>
      <div>
        <el-form ref="ruleFormRef" :model="form" label-width="80px">
          <el-form-item label="发票类型" prop="typeOfInvoiceIssued" :rules="[{required: true}]">
            <el-radio-group v-model="form.typeOfInvoiceIssued">
              <el-radio :value="1">纸质发票</el-radio>
              <el-radio :value="2">电子发票</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="form.typeOfInvoiceIssued == 2" label="上传方式" prop="invoiceUploadType" :rules="[{required: true, message: '请选择上传方式', trigger: 'blur'}]">
            <el-select v-model="form.invoiceUploadType" placeholder="请选择上传方式">
              <el-option label="文件上传" :value="1" />
              <el-option label="链接上传" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="form.invoiceUploadType == 1" label="上传发票" prop="invoiceUrl" :rules="[{required: true, message: '请上传发票', trigger: 'blur'}]">
              <el-upload
                v-model:file-list="fileList"
                class="upload-demo"
                action="#"
                accept=".png,.jpg,.jpeg,.ofd,.pdf,.HEIC,.zip"
                :on-remove="handleRemove"
                :limit="5"
                :http-request="toupload"
              >
                <el-button :disabled="fileList.length ? true : false" type="primary">点击上传</el-button>
                <template #tip>
                  <div class="el-upload__tip">
                    支持上传扩展名:png/jpg/jpeg/ofd/pdf/HEIC/zip文件
                  </div>
                </template>
              </el-upload>
            </el-form-item>
            <el-form-item 
            v-if="form.invoiceUploadType == 2"  
            v-for="(item,index) in form.domains" :key="index" 
            label="票据链接" 
            :prop="'domains.' + index + '.value'"
                :rules="{
                  required: true,
                  message: '请输入票据链接',
                  trigger: 'blur',
                }">
              <div class="flex justify-start items-center mb-3" style="width: 100%;">
                <el-input class="mr-3" v-model="item.value" placeholder="请输入票据链接" clearable/>
                <el-icon @click="addDomain" size="30" v-if="index == 0"><CirclePlus /></el-icon>
                <el-icon @click.prevent="removeDomain(item)" size="30" v-else><Remove /></el-icon>
              </div>
            </el-form-item>
            <el-col :span="10" :offset="6">
              <el-form-item label="">
                <div class="mt-6">
                  <el-button @click="modalOptions.modalValue = false">关闭</el-button>
                  <el-button @click="submitForm(ruleFormRef)" type="primary">
                    确认
                  </el-button>
                </div>
                
              </el-form-item>
            </el-col>
        </el-form>
      </div>
    </template>
    <!-- <template #footer>
      <vxe-button content="关闭" @click="modalOptions.modalValue = false" />
      <vxe-button
        v-if="modalOptions.canSubmit"
        status="primary"
        content="确定"
        @click="handleSubmit"
      />
    </template> -->
  </vxe-modal>
</template>
<style>
.form_header {
  font-size: 15px;
  color: #6379bb;
  border-bottom: 1px solid #ddd;
  padding-bottom: 5px;
}
.left-title {
  font-weight: 700;
  font-family: 微软雅黑;
  font-size: 14px;
  width: 85px;
  text-align: right;
}
.right-text {
  font-size: 14px;
}

</style>